import json

from rest_framework import serializers

from order.models import CouponModel, UserCoupon, OrderModel, OrderDetailModel, MyCourseModel


class CouponSerializer(serializers.ModelSerializer):
    class Meta:
        model = CouponModel
        fields = '__all__'


class UserCouponSerializer(serializers.ModelSerializer):
    coulist = serializers.SerializerMethodField(read_only=True)

    def get_coulist(self, obj):
        return {
            'id': obj.coupon.id,
            'name': obj.coupon.name,
            'condition': obj.coupon.condition,
            'price': obj.coupon.price,
            'start_time': obj.coupon.start_time,
            'end_time': obj.coupon.end_time,
        }

    class Meta:
        model = UserCoupon
        fields = '__all__'


class OrderSerializer(serializers.ModelSerializer):
    # orderdetailmodel_set = OrderDetailSerializer(many=True, read_only=True)
    courselist = serializers.SerializerMethodField(read_only=True)

    def get_courselist(self, obj):
        course = []
        for i in obj.orderdetailmodel_set.all():
            course.append({
                'id': i.id,
                'c_name': i.c_name,
                'price': i.price,
                'discount': i.discount,
                'cover': str(i.cover),
                'course': i.course.id,
            })
        return course

    class Meta:
        model = OrderModel
        fields = '__all__'


class OrderDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderDetailModel
        fields = '__all__'


class MyCourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyCourseModel
        fields = '__all__'
